<template>
  <div class="sale-container">
    <!-- 搜索表单区域 -->
    <el-card class="search-card" shadow="never">
      <el-form :inline="true" :model="QueryInfo" class="search-form">
        <el-form-item label="销售日期">
          <el-date-picker
            v-model="QueryInfo.SaleDate"
            type="date"
            placeholder="请选择销售日期"
            value-format="YYYY-MM-DD"
            style="width: 180px"
          />
        </el-form-item>
        <el-form-item label="单据号">
          <el-input v-model="QueryInfo.BillNo" placeholder="单据号" clearable style="width: 140px" />
        </el-form-item>
        <el-form-item label="客户">
          <el-select v-model="QueryInfo.CustomerId" placeholder="客户" clearable style="width: 140px">
            <el-option v-for="item in customerList" :key="item.Id" :label="item.Name" :value="item.Id" />
          </el-select>
        </el-form-item>
       
       
        <el-form-item label="收货地址">
          <el-input v-model="QueryInfo.Address" placeholder="收货地址" clearable style="width: 180px" />
        </el-form-item>
        <el-form-item label="销售员">
          <el-select v-model="QueryInfo.SalesmanId" placeholder="销售员" clearable style="width: 120px">
            <el-option v-for="item in userList" :key="item.UserId" :label="item.UserName" :value="item.UserId" />
          </el-select>
        </el-form-item>
        <el-form-item label="审核状态">
          <el-radio-group v-model="QueryInfo.Status">
            <el-radio :label="''">全部</el-radio>
            <el-radio label="未审核">未审核</el-radio>
            <el-radio label="已审核">已审核</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchList">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区块 -->
    <div class="action-bar">
      <el-button type="primary" @click="addPopup">新增</el-button>
      <el-button type="danger" :disabled="!hasSelection" @click="batchDeleteSale">批量删除</el-button>
      <el-button :disabled="!hasSelection">审核</el-button>
      <el-button :disabled="!hasSelection">财务审核</el-button>
      <el-button :disabled="!hasSelection">仓库审核</el-button>
    </div>

    <!-- 数据表格 -->
    <el-table :data="tableData" border stripe highlight-current-row v-loading="loading" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" />
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column prop="SaleDate" label="销售日期" width="120" align="center">
        <template #default="scope">
          {{ scope.row.SaleDate ? scope.row.SaleDate.slice(0, 10) : '' }}
        </template>
      </el-table-column>
      <el-table-column prop="OrderNumber" label="单据号" width="120" align="center" />
      <el-table-column prop="CustomerName" label="客户" width="120" align="center" />
     
     
      <el-table-column prop="TransactionPrice" label="总成交价(元)" width="120" align="center" />
      <el-table-column prop="Status" label="审核状态" width="100" align="center" />
      <el-table-column prop="EarNumber" label="耳号" width="100" align="center" />
      <el-table-column prop="TransactionPrice" label="成交价(元)" width="100" align="center" />
      <el-table-column prop="FixedPrice" label="定价(元)" width="100" align="center" />
      <el-table-column prop="Address" label="收货地址" width="140" align="center" />
      <el-table-column prop="SalesmanName" label="销售员" width="100" align="center" />
      <el-table-column prop="CreateUserId" label="创建人" width="100" align="center" />
      <el-table-column prop="CreateTime" label="创建时间" width="160" align="center">
        <template #default="scope">
          {{ scope.row.CreateTime ? scope.row.CreateTime.slice(0, 10) : '' }}
        </template>
      </el-table-column>
      
      <el-table-column label="操作" width="100" align="center">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="editSale(scope.row)">编辑</el-button>
          <el-button link type="danger" size="small" @click="deleteSale(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-section">
      <el-pagination
        v-model:current-page="QueryInfo.PageIndex"
        v-model:page-size="QueryInfo.PageSize"
        :page-sizes="[10, 15, 20, 50, 100]"
        layout="sizes, prev, pager, next, jumper, total"
        :total="QueryInfo.TotalCount"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { serviceRead, Sheep_BreedingWrite } from '@/utils/Interceptors';
import { useRouter } from 'vue-router';

const router = useRouter();
const loading = ref(false)
const tableData = ref<any[]>([])
const hasSelection = ref(false)
const selectedRows = ref<any[]>([])
const customerList = ref<any[]>([])
const salesmanList = ref<any[]>([])
const userList = ref<any[]>([])

const QueryInfo = reactive({
  SaleDate: '',
  BillNo: '',
  CustomerName: '',
  EarNo: '',
  Department: '',
  Address: '',
  SalesmanId: '',
  Status: '',
  PageIndex: 1,
  PageSize: 20,
  TotalCount: 0,
  CustomerId: '',
})

const fetchCustomerList = () => {
  Sheep_BreedingWrite.get('/api/Customer/GetCustomerList').then(res => {
    if (res.data && res.data.code === 200) {
      customerList.value = res.data.data || []
    } else {
      customerList.value = []
    }
  })
}

const fetchSalesmanList = () => {
  Sheep_BreedingWrite.get('/api/Salesman/GetSalesmanList').then(res => {
    if (res.data && res.data.code === 200) {
      salesmanList.value = res.data.data || []
    } else {
      salesmanList.value = []
    }
  })
}

const fetchUserList = () => {
  serviceRead.get('/api/User/SraechUser').then(res => {
    if (res.data && res.data.code === 200) {
      userList.value = res.data.PageData || []
    } else {
      userList.value = []
    }
  })
}

const fetchList = () => {
  loading.value = true
  let params: any = { ...QueryInfo }
  if (QueryInfo.SaleDate) {
    params.SaleDate = QueryInfo.SaleDate
  } else {
    params.SaleDate = ''
  }
  Sheep_BreedingWrite.get('/api/SheepSale/SearchSheepSale', { params }).then(res => {
    if (res.data && res.data.code === 200) {
      tableData.value = res.data.data || []
      QueryInfo.TotalCount = res.data.total || 0
    } else {
      tableData.value = []
      QueryInfo.TotalCount = 0
    }
    loading.value = false
  })
}

const addPopup = () => {
  router.push('/SaleAddView')
}

const deleteSale = (row: any) => {
  ElMessageBox.confirm('是否删除当前销售信息？', '删除确认', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    Sheep_BreedingWrite.delete('/api/SheepSale/DeleteSheepSale', { params: { Id: row.Id } }).then(res => {
      if (res.data && res.data.code === 200) {
        ElMessage.success(res.data.msg || '删除成功')
        fetchList()
      } else {
        ElMessage.error(res.data.msg || '删除失败')
      }
    })
  })
}

const editSale = (row: any) => {
  router.push({ name: 'SaleAddView', query: { id: row.Id } })
}

const batchDeleteSale = () => {
  if (!selectedRows.value.length) {
    ElMessage.warning('请先选择要删除的记录')
    return
  }
  ElMessageBox.confirm('是否批量删除选中的销售信息？', '批量删除确认', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    const ids = selectedRows.value.map((row: any) => row.Id)
    Sheep_BreedingWrite.delete('/api/SheepSale/BatchDeleteSheepSale/BatchDelete', { params: { ids: ids.join(',') } }).then(res => {
      if (res.data && res.data.code === 200) {
        ElMessage.success(res.data.msg || '批量删除成功')
        fetchList()
      } else {
        ElMessage.error(res.data.msg || '批量删除失败')
      }
    })
  })
}

const handleSizeChange = (val: number) => {
  QueryInfo.PageSize = val
  fetchList()
}
const handleCurrentChange = (val: number) => {
  QueryInfo.PageIndex = val
  fetchList()
}
const handleSelectionChange = (rows: any[]) => {
  selectedRows.value = rows
  hasSelection.value = rows.length > 0
}

onMounted(() => {
  fetchCustomerList()
  fetchUserList()
  fetchList()
})
</script>

<style scoped>
.sale-container {
  min-height: 100vh;
  background: #fff;
  padding: 0 0 24px 0;
}
.search-card {
  margin: 16px 16px 0 16px;
  padding: 12px 24px 0 24px;
}
.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 8px 24px;
}
.action-bar {
  margin: 12px 16px 0 16px;
  display: flex;
  gap: 8px;
}
.table-section {
  margin: 0 16px;
}
.pagination-section {
  margin: 16px 16px 0 0;
  text-align: right;
}
</style> 